﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Anke.SHManage.Model.ViewModel;
using Anke.SHManage.BLL;
using Anke.SHManage.Model.EasyUIModel;
using Anke.SHManage.Model;
using Anke.SHManage.Utility;
using System.Data.SqlClient;
using System.Data;
using Anke.SHManage.MSSQLDAL;
using System.Web.Script.Serialization;
using System.Configuration;

namespace Anke.SHManage.Web.Controllers
{
    public class HomeController : Controller
    {
        private JavaScriptSerializer js = new JavaScriptSerializer();

        /// <summary>
        /// 用户登录Get请求页面
        /// </summary>
        /// <returns></returns>
        [SkipLoginAttribute]
        public ActionResult UserLogin()
        {
            return View();
        }
        /// <summary>
        /// 用户登录首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Home()
        {
            ViewBag.lname = UserOperateContext.Current.Session_UsrInfo.Name;

            string selfWorkCode = UserOperateContext.Current.Session_UsrInfo.WorkCode;
            string selfStationID = new PersonalStatisticsBLL().GetstaionCodeByWorkCodeTAmbulance(selfWorkCode);
            string selfCenterID = UserOperateContext.Current.Session_UsrInfo.P_Department.DispatchSubCenterID;
              //new PersonalStatisticsBLL()
            if (selfStationID != null && selfStationID != "")
            {
                ViewBag.selfName = UserOperateContext.Current.Session_UsrInfo.Name +"月工作信息";
            }
            else if (selfCenterID != null && selfCenterID != "")
            {
                string selfCenterName = "";
                switch (selfCenterID)
                {
                    case "1": selfCenterName = "中心";
                        break;
                    case "2": selfCenterName = "中区";
                        break;
                    case "3": selfCenterName = "东区";
                        break;
                    case "4": selfCenterName = "南区";
                        break;
                    case "5": selfCenterName = "西区";
                        break;
                    case "6": selfCenterName = "北区";
                        break;
                    default: break;
                }
                ViewBag.selfName = selfCenterName+"月工作信息";
            }
            else {
                ViewBag.selfName = "全中心月工作信息";
            }

            ViewBag.ltime = DateTime.Now;
            return View();
        }
        ///// <summary>
        ///// 根据双杨要求workcode实际传为LoginName
        ///// </summary>
        ///// <param name="workcode"></param>
        ///// <returns></returns>
        //[HttpGet]
        //[SkipLoginAttribute]
        //public ActionResult UrlLogin(string loginname, string urllogin)
        //{
        //    LoginUserBLL bll = new LoginUserBLL();
        //    if (bll.Login(loginname))
        //    {
        //        //StateLog("登录", loginname);//20151117增加状态日志--20160929注释
        //        //LogUtility.Debug("用户[" + loginname + "]跳转--登录业务系统成功！", "");//20151110增加用户登录成功日志
        //        //登录成功，跳转到主页面
        //        return Redirect("~/Home/Index?urllogin=" + urllogin);
        //    }
        //    else
        //    {
        //        JavaScriptResult js = new JavaScriptResult();
        //        js.Script = "alert('业务系统未找到[" + loginname + "]登录人！')";
        //        //LogUtility.Debug("业务系统未找到[" + loginname + "]登录人！", "");//20151110增加用户登录失败日志
        //        return js;
        //    }
        //}

        ///// <summary>
        ///// 提交登录请求
        ///// </summary>
        ///// <param name="info">登录实体</param>
        ///// <returns></returns>
        //[HttpPost]
        //[SkipLoginAttribute]
        //public ActionResult UserLoginByInfo(LoginInfo info)
        //{
        //    //首先检查用户名密码
        //    LoginUserBLL bll = new LoginUserBLL();
        //    if (bll.Login(info.LoginName, info.PassWord))
        //    {
        //        //StateLog("登录", info.LoginName);//20151117增加状态日志--20160929注释
        //        //LogUtility.Debug("用户[" + info.LoginName + "]直接--登录业务系统成功！", "");//20151110增加用户登录成功日志
        //        //登录成功，跳转到主页面
        //        return this.JsonResult(E_JsonResult.OK, "", null, "~/Home/Index");
        //    }
        //    else
        //    {
        //        //LogUtility.Debug("用户[" + info.LoginName + "]直接--登录失败！用户名或者密码错误！", "");//20151110增加用户登录失败日志
        //        //登录失败,发送错误错误给用户
        //        return this.JsonResult(E_JsonResult.Error, "登录失败！用户名或者密码错误！", null, null);
        //    }
        //}
        /// <summary>
        /// 提交登录请求 
        /// edit2023-06-14 plq 登录添加登录失败次数记录与限制
        /// 参考闵行移植
        /// </summary>
        /// <param name="info">登录实体</param>
        /// <returns></returns>
        [HttpPost]
        [SkipLoginAttribute]
        public ActionResult UserLoginByInfo(LoginInfo info)
        {
            if (UserOperateContext.Current.Session_UsrInfo != null)
            {
                if (UserOperateContext.Current.Session_UsrInfo.LoginName != info.LoginName)
                {
                    JsonResult jsr = this.JsonResult(E_JsonResult.Error, "此电脑已存在登录的账户,登录人: " + UserOperateContext.Current.Session_UsrInfo.Name + " ,请先退出已有账户，再进行登录！", null, null);
                    jsr.ContentType = "text/html";
                    return jsr;
                }
            }
            //首先检查用户名密码
            LoginUserBLL bll = new LoginUserBLL();
            int LoginErrCount = 1; //增加登录失败m次后n分钟内限制登录的功能 add2021-09-23 plq
            DateTime datatimes = DateTime.Now;
            //查询是否重复登录失败次数
            P_Login_Err errInfo = bll.GetLoginErrInfo(info.LoginName);
            if (errInfo != null)
            {
                datatimes = errInfo.LoginTime;//最后一次登录失败的时间
                LoginErrCount = errInfo.LoginErrNum + 1;
            }
            int datediff = Timediff(datatimes);
            //获取登录次数，禁止登录时间分钟；
            int LoginFailCount = AppConfig.GetConfigInt("FailCount");
            int LoginFailStopTime = AppConfig.GetConfigInt("FailStopTime");
            if (LoginErrCount > LoginFailCount && (datediff < LoginFailStopTime))
            {
                StateLog("登录已锁定", info.LoginName);//20151117增加状态日志--20160929注释
                JsonResult jsr = this.JsonResult(E_JsonResult.Error, "用户登录" + LoginFailCount + "次失败" + "；请等待" + (LoginFailStopTime - datediff) + "分钟！", null, null);
                jsr.ContentType = "text/html";
                return jsr;
            }
            else
            {
                if (datediff >= LoginFailStopTime) // 登录失败多次后的禁止登录时间已过，失败次数重新累计
                {
                    bll.LoginClearErrCount(info.LoginName, "PC");
                    LoginErrCount = 1;
                }

                if (bll.Login(info.LoginName, info.PassWord)) //用户验证通过，登录成功
                {
                    StateLog("登录成功", info.LoginName);//20151117增加状态日志--20160929注释
                    //成功登录，清除错误登录数据 add2021-09-22 plq
                    bll.LoginClearErr(info.LoginName);

                    //等保要求：用户密码有效期验证天数限制改密 add2024-07-15 plq
                    //获取用户密码有效期天数配置，大于0则表示密码过了有效期要提示改密重登
                    int config_UserPwdValidityDays = AppConfig.GetConfigInt("UserPwdValidityDays");
                    DateTime UserLastUpdatePwdTime = DateTime.Now;
                    if (UserOperateContext.Current.Session_UsrInfo != null && UserOperateContext.Current.Session_UsrInfo.LastUpdatePwdTime != null)
                    {
                        UserLastUpdatePwdTime = (DateTime)UserOperateContext.Current.Session_UsrInfo.LastUpdatePwdTime;
                    }
                    bool IsPwdExpired = false;
                    if (config_UserPwdValidityDays > 0)
                    {
                        IsPwdExpired = TimeDayDiff(UserLastUpdatePwdTime) >= config_UserPwdValidityDays; //密码是否已过有效天数，需要改密 add2024-07-15 plq
                    }
                    var _resMsg = IsPwdExpired ? string.Format("您的密码有效期已过{0}天,请修改密码后再登录", config_UserPwdValidityDays) : ""; //add2024-07-15 plq

                    //登录成功，跳转到主页面
                    JsonResult jsr = this.JsonResult(E_JsonResult.OK, "", new { isPwdExpired = IsPwdExpired, msg = _resMsg }, "~/Home/Index");
                    jsr.ContentType = "text/html";
                    return jsr;
                }
                else //用户验证失败
                {
                    StateLog("登录失败", info.LoginName);//20151117增加状态日志--20160929注释
                    //数据库记录一次登录失败
                    bll.LoginErrCount(info.LoginName, "PC");

                    JsonResult jsr = this.JsonResult(E_JsonResult.Error, "用户名或密码错误！用户登录" + LoginErrCount + "次失败" + "；请重新输入！", null, null);
                    jsr.ContentType = "text/html";
                    return jsr;
                }
            } 
        }

        //20151117增加状态日志
        public int StateLog(string Description, string LoginName)
        {
            TStateLog model = new TStateLog();//20151117增加登录状态日志
            model.Description = Description;//状态
            model.OperationTime = DateTime.Now;//时间
            model.OperationPerson = LoginName;//操作人
            int res = new TStateLogBLL().Add(model.ToPOCO());
            return res;
        }
        /// <summary>
        /// 加载主页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(string urllogin)
        {
            if (urllogin == null)
                ViewBag.urllogin = Url.Content("~/Home/RedirectToLogin");
            else
                ViewBag.urllogin = urllogin;
            ViewBag.LoginName = UserOperateContext.Current.Session_UsrInfo.Name;
            ViewBag.LoginNameNew = UserOperateContext.Current.Session_UsrInfo.LoginName;

            ViewBag.WorkCode = UserOperateContext.Current.Session_UsrInfo.WorkCode; //add2021-05-10 plq 取当前登录人工号
            //判断登录人有无访问市120开发管理系统的权限 add2021-05-10 plq
            UserOperateContext userOperateContext = new UserOperateContext();
            bool Insert = userOperateContext.getGongneng(AppConfig.GetConfigInt("City12PermissionID"));
            if (Insert)
            {
                ViewBag.RoleFAPermissionInsert = "Insert";
            }
            //判断登录人有无访问医保相关的权限 add2021-09-10 sr //add2021-10-18 plq 医保上线移植
            bool YBRole = userOperateContext.getGongneng(AppConfig.GetConfigInt("YBRole"));
            if (YBRole)
            {
                ViewBag.YBRole = "Insert";
            }
            ViewBag.FAUrl = AppConfig.GetConfigString("City120FAUrl"); //访问Url

            return View();
        }

        /// <summary>
        /// 获取权限菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult getMenuData()
        {
            /*
             *  ToDo：
                    1.把需要显示的权限菜单显示到UI左侧菜单树中   
                    2.把url 属性添加到attribute的 url 属性中 用 tabs 容器包裹 iframe 标签实现 多tab页面展现 
             */
            return Content(UserOperateContext.Current.Session_UserTreeJsonStr);  //把用户权限菜单
        }

        /// <summary>
        /// Filters跳转到登录页面
        /// </summary>
        /// <returns></returns>
        [SkipLoginAttribute]
        public ActionResult RedirectToLogin()
        {
            return View();
        }

        //修改密码 dyq 2018-10-17
        public ActionResult UpdatePwd(string NewPwd)
        { 
            string NewPwdMd5 = SecurityHelper.GetMD5(NewPwd);  //MD5
            string IdCard = UserOperateContext.Current.Session_UsrInfo.LoginName; //add2021-06-21 plq 三级等保测试高危--垂直越权---避免IdCard前端传参被篡改，改为后台自动获取当前用户的登录名
            DateTime DtNow = DateTime.Now;
            //2019-06-13 plq 修改密码无效bug修复---数据库连接字符串配置问题
            //SqlConnection connection = new SqlConnection("server=IRIS-PC;uid=sa;pwd=anchor;database=AKV7Manage");
            SqlConnection connection = new SqlConnection(SqlHelper.MainConnectionString); //直接调用config里的主数据库连接字符串--不用再自己写
            connection.Open();
            string sql = "update P_User set PassWord=@PassWord,LastUpdatePwdTime=@LastUpdatePwdTime where LoginName=@LoginName";
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.Add(new SqlParameter("@LoginName", IdCard.ToString()));  //指定参数
            cmd.Parameters.Add(new SqlParameter("@PassWord", NewPwdMd5.ToString()));  //指定参数
            cmd.Parameters.Add(new SqlParameter("@LastUpdatePwdTime", DtNow.ToString()));  //指定参数---最后改密时刻 add2024-07-15 plq 安测定期改密要求
            int rows = cmd.ExecuteNonQuery();  //执行并返回影响行数
            if (rows > 0)
            {
                StateLog("修改密码", IdCard); //2019-10-22 plq 记录修改密码成功状态日志

                //清除session---防止原链接仍可进入首页
                Session.Remove("UserInfo"); //只清除用户信息session相关
                Session.Abandon();//清除所有session
                return Json("OK");
            }
            else
            {
                return Json("NO");
            }
            
        }

        #region 退出登录 add2021-06-08 plq

        public ActionResult ExitLogin(string LoginName)
        {
            int num = StateLog("退出登录", LoginName); //记录退出登录状态日志,成功返回1
            if (num > 0) //若记录状态成功
            {
                //清除session---防止原链接仍可进入首页
                //Session.Abandon();//清除所有session
                Session.Remove("UserInfo"); //只清除用户信息session相关
                return Json("OK");
            }
            else
            {
                return Json("NO");
            }
        }

        #endregion

        #region 调度下挂页面

        /// <summary>
        /// 调度台下挂连接  无需登录，突发事件列表页 下挂链接 2020-12-22 plq
        /// </summary>
        /// <param name="WorkCode"></param>
        /// <param name="PassWord"></param>
        [HttpGet]
        [SkipLoginAttribute]
        public void AccidentEventForDD(string WorkCode)
        {
            if (WorkCode == "")
            {
                string aspxUrl = "~/Home/error?message=登录失败！工号错误";
                Response.Redirect(aspxUrl);
            }
            //首先检查用户名密码
            LoginUserBLL bll = new LoginUserBLL();
            if (bll.LoginByWorkCode(WorkCode))
            {
                //string aspxUrl = "~/DD/Emergency/AccidentEvent"; //突发事件列表页
                string aspxUrl = "~DD/MajorEvent/MajorEvent"; //适配V7奉贤页面
                Response.Redirect(aspxUrl);
            }
            else
            {
                string aspxUrl = "~/Home/error?message=登录失败！工号错误";
                Response.Redirect(aspxUrl);
            }
        }

        /// <summary>
        /// 调度台下挂连接  无需登录，事件详细页面 下挂链接 2020-12-22 plq
        /// </summary>
        /// <param name="WorkCode"></param>
        /// <param name="EventCode"></param>
        [HttpGet]
        [SkipLoginAttribute]
        public void EventInfoForDD(string WorkCode, string EventCode)
        {
            if (WorkCode == "")
            {
                string aspxUrl = "~/Home/error?message=登录失败！工号错误";
                Response.Redirect(aspxUrl);
            }
            //首先检查用户名密码
            LoginUserBLL bll = new LoginUserBLL();
            if (bll.LoginByWorkCode(WorkCode))
            {
                string aspxUrl = "~/DD/AcceptEvent/AcceptEventTaskList?EventCode=" + EventCode; //事件详细页面
                Response.Redirect(aspxUrl);
            }
            else
            {
                string aspxUrl = "~/Home/error?message=登录失败！工号错误";
                Response.Redirect(aspxUrl);
            }
        }

        /// <summary>
        /// 调度台下挂连接  无需登录，首页页面 下挂链接 2020-12-22 plq
        /// </summary>
        /// <param name="WorkCode"></param>
        [HttpGet]
        [SkipLoginAttribute]
        public void IndexForDD(string WorkCode)
        {
            if (WorkCode == "")
            {
                string aspxUrl = "~/Home/error?message=登录失败！工号错误";
                Response.Redirect(aspxUrl);
            }
            //首先检查用户名密码
            LoginUserBLL bll = new LoginUserBLL();
            if (bll.LoginByWorkCode(WorkCode))
            {
                string aspxUrl = "~/Home/Index"; //首页
                Response.Redirect(aspxUrl);
            }
            else
            {
                string aspxUrl = "~/Home/error?message=登录失败！工号错误";
                Response.Redirect(aspxUrl);
            }
        }

        #endregion

        #region 2021-09-03 SR  医保web登录接口 //add2021-10-18 plq 医保上线移植
        /// <summary>
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Boolean UrlLogin(string loginName, string pwd)
        {
            try
            {
                string strURL = ConfigurationManager.AppSettings["YBWebUrlLogin"].ToString();
                string parm = "loginname=" + loginName + "&loginpwd=" + pwd;
                string ret = HttpWebBLL.GetHttp(strURL, parm);
                //解析返回的实体
                ResultInfo rinfo = js.Deserialize<ResultInfo>(ret);
                if (rinfo.status == "0")
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
            catch (Exception ex)
            {
                LogUtility.Error("HomeController/UrlLogin", "程序异常：" + ex.Message);
                return false;
            }
        }
        #endregion

        #region 新用户登录页相关 add2023-06-12 plq

        /// <summary>
        /// 用户登录页--新
        /// add2021-07-27 plq
        /// </summary>
        /// <returns></returns>
        [SkipLoginAttribute]
        public ActionResult UserLoginNew()
        {
            return View();
        }

        /// <summary>
        /// 根据登录名修改密码
        /// add2021-07-27 plq
        /// </summary>
        /// <param name="NewPwd"></param>
        /// <param name="IdCard"></param>
        /// <returns></returns>
        public ActionResult UpdatePwdByLoginName(string NewPwd, string LoginName)
        {
            string NewPwdMd5 = SecurityHelper.GetMD5(NewPwd);  //MD5
            DateTime DtNow = DateTime.Now;
            SqlConnection connection = new SqlConnection(SqlHelper.MainConnectionString);
            connection.Open();
            string sql = "update P_User set PassWord=@PassWord,LastUpdatePwdTime=@LastUpdatePwdTime where LoginName=@LoginName";
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.Add(new SqlParameter("@LoginName", LoginName.ToString()));  //指定参数
            cmd.Parameters.Add(new SqlParameter("@PassWord", NewPwdMd5.ToString()));  //指定参数
            cmd.Parameters.Add(new SqlParameter("@LastUpdatePwdTime", DtNow.ToString()));  //指定参数---最后改密时刻 add2024-07-15 plq 安测定期改密要求
            int rows = cmd.ExecuteNonQuery();  //执行并返回影响行数
            if (rows > 0)
            {
                StateLog("修改密码", LoginName); //2019-10-22 plq 记录修改密码成功状态日志

                //清除session---防止原链接仍可进入首页
                Session.Remove("UserInfo"); //只清除用户信息session相关
                Session.Abandon();//清除所有session
                return Json("OK");
            }
            else
            {
                return Json("NO");
            }

        }

        /// <summary>
        /// 计算该时间到当前时间的时间间隔(分钟数)
        /// add2021-09-21 plq
        /// </summary>
        /// <param name="t0"></param>
        /// <returns></returns>
        private int Timediff(DateTime t0)
        {
            DateTime t1 = DateTime.Now;
            TimeSpan ts = t1 - t0;
            return (int)(ts.TotalMinutes);
        }

        /// <summary>
        /// 计算该时间到当前时间的时间间隔(天数)
        /// add2024-07-15 plq
        /// </summary>
        /// <param name="t0"></param>
        /// <returns></returns>
        private int TimeDayDiff(DateTime t0)
        {
            DateTime t1 = DateTime.Now;
            TimeSpan ts = t1 - t0;
            return (int)(ts.TotalDays);
        }
        #endregion

    }
}
